#ifndef __UserLoginSection2_HPP__
#define __UserLoginSection2_HPP__

#include "MySQLClient.hpp"
#include "TcpConnection.hpp"
#include "Packet.hpp"
#include "TLV.hpp"
#include "logger.hpp"
#include <string.h>

class UserLoginSection2
{
public:
    UserLoginSection2(wd::TcpConnectionPtr conn,Packet pack ):_conn(conn),_packet(pack){

    }
    ~UserLoginSection2() {}

    void process(){
        using namespace wd;
        using namespace std;
        //1.解码
        //(1)判断类型
        if(_packet.type != TASK_LOGIN_SECTION2){
            MyLogger::getInstance().serverError("Packet type error!");
            return;
        }
        //(2)获得密文
        string msg = _packet._msg;
        MyLogger::getInstance().serverInfo("用户发送加密密文: "+ msg);
        

        //2.(1)获取盐值,盐值形式是 $1$salt$
        string setting = getSetting(msg);

        //(2).MySQL查询,获取数据库密文
        wd::MySQLClient myclient;
        bool ret = myclient.connect("localhost", 3306, "root", "1234",
                                    "shms");
        if(!ret) {
            exit( EXIT_FAILURE);
        }
        string  encrypt = myclient.getEncrypt(setting);        

        //3.编码tlv
        TLV tlv;
        if(encrypt == "" || encrypt != msg){
            tlv.type = TASK_LOGIN_SECTION2_RESP_ERROR;
            tlv.length = 0;
            const char * buf= "login failed";
            tlv.length = strlen(buf);
            strcpy(tlv.data,buf);
        }else if(encrypt == msg)
        {
            tlv.type = TASK_LOGIN_SECTION2_RESP_OK;
            const char * buf= "login success";
            tlv.length = strlen(buf);
            tlv.setData(buf);
            strcpy(tlv.data,buf);
        }
        //4.发送到eventloop中

        _conn->sendInLoop(tlv);
    }

private:
    string getSetting(const string & msg)
    {
        string res;
        int i,j;
        //取出salt,i 记录密码字符下标，j记录$出现次数
        for(i = 0,j = 0;msg[i]&& j!=3;++i)
        {
            if(msg[i] == '$')
                ++j;
        }
        return string(msg,0,i);
    }
private:
    wd::TcpConnectionPtr _conn;
    Packet _packet; 
};

#endif
